package com.twb.auth.aspect;

import com.twb.auth.security.TwbSystemSecurityUtil;
import com.twb.core.security.TwbSecurityUtil;
import com.twb.core.security.annotation.Auth;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.InitBinder;

/** 
 * @ClassName TwbTokenSecurityAspect 
 * @Description token验证拦截器
 * @author DSY
 * @date 2018年12月3日 上午10:12:40 
 */ 
public class TwbSecurityAspect {
	
	private final Logger logger = LoggerFactory.getLogger(TwbSecurityAspect.class);
	@Autowired
	HttpServletRequest request;
	@Autowired
	HttpServletResponse response;
	@Autowired
	TwbSecurityUtil twbSecurityUtil;
	@Autowired
	TwbSystemSecurityUtil twbSystemSecurityUtil;
	
	public Object execute(ProceedingJoinPoint pjp) throws Throwable {
		// 从切点上获取目标方法
		MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
		Method method = methodSignature.getMethod();

		// 属性编辑器直接放行
		InitBinder initBinder = method.getAnnotation(InitBinder.class);
		if(initBinder != null){
			// 调用目标方法
			return pjp.proceed();
		}

		// 判断目标方法是否有登录验证，如果没有登录验证，则直接调用方法。默认做登录验证
		Auth auth = method.getAnnotation(Auth.class);
		if (auth == null || auth.verifyApp()) {
			logger.debug("【APP 接入验证】" + request.getServletPath());
			twbSystemSecurityUtil.checkProject(request);
		}
		if (auth == null || (auth.verifyApp()&&auth.verifyToken())) {
			logger.debug("【TOKEN 验证】" + request.getServletPath());
			twbSecurityUtil.checkAndRefreshToken(request);
		}
		if (auth == null || (auth.verifyApp() && auth.verifyToken() && auth.verifyURL())) {
			logger.debug("【URL 验证】" + request.getServletPath());
			twbSystemSecurityUtil.checkUrl(request);
		}
		// 调用目标方法
		return pjp.proceed();
	}
}
